package com.zidian.study.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.zidian.study.activity.InteractionAskDetailActivity;
import com.zidian.study.adapter.TaskWorkAdapter;
import com.zidian.study.bean.TaskActionBean;
import com.zidian.study.bean.TaskWorkBean;
import com.zidian.study.globa.BaseFragment;
import com.zidian.study.globa.Constant;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import okhttp3.Call;

import com.zidian.student.trucks.R;

/**
 * Created by Administrator on 2016/8/26 0026.
 */
public class TaskWorkFragment extends BaseFragment {

    @Bind(R.id.no_data_view)
    LinearLayout noDataView;

    public SwipeRefreshLayout mSwipeRefreshWidget;
    private RecyclerView mRecyclerView;


    private boolean isLoading;
    private boolean isRefreshing = false;
    private List<TaskWorkBean.DataBean> data = new ArrayList<>();
    private TaskWorkAdapter adapter;
    private Handler handler = new Handler();
    private int row = 1;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_work;
    }


    public static TaskWorkFragment newInstance() {

        return new TaskWorkFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {


        adapter = new TaskWorkAdapter(getActivity(), data);
        mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.list);

        initView();
        initData();


    }

    public void initView() {

        mSwipeRefreshWidget.setColorSchemeResources(R.color.green);

        mSwipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshWidget.setRefreshing(true);
                isRefreshing = true;
            }
        });
        mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        data.clear();
                        isRefreshing = true;
                        try {
                            row = 1;
                            getData(row + "");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, 2000);
            }
        });
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = mSwipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    row++;
                                    getData(row + "");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });


        //添加点击事件
        adapter.setOnItemClickListener(new TaskWorkAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d("test", "item position = " + position);
                startActivity(InteractionAskDetailActivity.class);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

    }

    public void initData() {
        try {
            getData(row + "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private List<TaskActionBean.DataBean> dataBeanList = new ArrayList<>();

    /**
     * 学生作业查询
     *
     * @param startrow
     * @throws IOException
     */
    public void getData(String startrow) throws IOException {
        String url = Constant.URL_GOAL + "studentWork/select";

        Map<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("studentId", GetUserInfo.getStudentId(mActivity));
        map.put("token", GetUserInfo.getToken(mActivity));


        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
                Log.e("E", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                isRefreshing = false;
                mSwipeRefreshWidget.setRefreshing(false);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(mActivity.getApplication(), jsonObject.getString("message"));
                        noDataView.setVisibility(View.VISIBLE);
                        return;
                    }

                } catch (JSONException e) {


                }

                Gson gson = new Gson();
                TaskWorkBean workBean = gson.fromJson(response, TaskWorkBean.class);

                if (workBean.isSuccess()) {
                    if (workBean.getData().size() < 10) {
                        isLoading = true;
                        adapter.setMore(false);
                    } else {
                        isLoading = false;
                        adapter.setMore(true);
                    }
                    data.addAll(workBean.getData());
                    adapter.notifyDataSetChanged();
                    adapter.notifyItemRemoved(adapter.getItemCount());
                    noDataView.setVisibility(View.GONE);
                }

            }
        });

    }

}
